/**
 * @Author Fizz Pu
 * @Date 2021/3/6 下午3:27
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */
// 排列问题


import java.util.*;

public class Leetoffer1  {
    public static void main(String[] args) {
        new Leetoffer1().permute(new int[]{1, 2 ,3});
    }

    public List<List<Integer>> permute(int[] nums) {

        List<List<Integer>> res = new ArrayList<>();
        int[] visited = new int[nums.length];
        backtrack(res, nums, new ArrayList<>(), visited);
        return res;

    }

    private void backtrack(List<List<Integer>> res, int[] nums, ArrayList<Integer> tmp, int[] visited) {
        if (tmp.size() == nums.length) {
            res.add(new ArrayList<>(tmp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (visited[i] == 1) continue;
            visited[i] = 1;
            tmp.add(nums[i]);
            backtrack(res, nums, tmp, visited);
            visited[i] = 0;
            tmp.remove(tmp.size() - 1);
            // tmp.remove(nums[i]); 优先使用下标
        }
    }
}